package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbUser;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.utils.SendMobileCodeUtil;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.PageOrderVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-04-21 10:08:12
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService {

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IUserService iUserService;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getOrderById(Integer id) {
        //-- 获取订单信息
        TbOrder tbOrder = tbOrderMapper.selectById(id);
        if (tbOrder == null) {
            return R.ERROR(404, "订单不存在");
        }

        //-- 获取用户信息
//        String url = "http://localhost:9001/user/index/getUserById/" + tbOrder.getUserId();
//        R r = restTemplate.postForObject(url, null, R.class);
        R r = iUserService.getUserById(tbOrder.getUserId());
        if(r.getCode() != 200) {
            return r;
        }

        String u = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(u, TbUser.class);

        //-- 返回订单信息
        tbOrder.setUser(tbUser);
        return R.OK(tbOrder);
    }

    @Override
    public R getOrderList(PageOrderVo pageInfoVo) {
        // 构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        // 查询条件
//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        if(pageInfoVo.getStatus() != null) {
//            wrapper.lambda().eq(TbOrder::getOrderStatus, pageInfoVo.getStatus());
//        }
//
//        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
//            wrapper.lambda().like(TbOrder::getOrderCode, pageInfoVo.getKeyWord());
//        }

        // 排序
//        wrapper.lambda().orderByDesc(TbOrder::getOrderId);

        // 分页查询
        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page, pageInfoVo.getKeyWord(), pageInfoVo.getStatus());

        // 返回分页数据
        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(List<TbProd> prodList) {
        //-- 获取用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        //-- 扣减库存 TODO



        //-- 生成订单，并保存
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderStatus(0);

        // 订单编号： yyyyMMddHHmmss + 6位随机数
        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        code += RandomUtil.randomNumbers(6);

        tbOrder.setOrderCode(code);
        tbOrder.setUserId(userId);
        tbOrder.setCreateTime(new Date());

        Double amount = 0.0;
        Integer num = 0;
        for (TbProd tbProd : prodList) {
            amount = amount + tbProd.getProdPrice() * tbProd.getBuyNum();
            num += tbProd.getBuyNum();
        }

        tbOrder.setAmount(amount);
        tbOrder.setProdCount(num);

        tbOrderMapper.insert(tbOrder);

        //-- 保存订单明细
        for (TbProd tbProd : prodList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setProdId(tbProd.getProdId());
            tbOrderDetail.setBuyNum(tbProd.getBuyNum());
            tbOrderDetail.setProdPrice(tbProd.getProdPrice());
            tbOrderDetail.setOrderId(tbOrder.getOrderId());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        return R.OK();
    }

    @Override
    public R sendMobileCode(String mobile, String code) {
        Boolean ok = SendMobileCodeUtil.sendMobileCode(mobile, code);
        if(!ok) {
            return R.ERROR(500, "短信发送失败");
        }
        return R.OK();
    }
}





